// pages/topic-another/topic-another.js
import ajax from "../../utils/ajax";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    paperDetail:{},
    question: {},
    questionList:[],
    percent: '10',
    timeRemain:'',
    number:1,
    total:93,
    time: 0,
    subTime: 0,
    duration:0,
    type:1,
    testId: '',
    answerList: [],
    answerResult: {},
    nextShow: true
  },
  onLoad: function (e) {
  const type = e?.type??1
   let userInfo = wx.getStorageSync("userInfo");
   const mentalId =wx.getStorageSync('mentalId')||''
   const anotherType = wx.getStorageSync('anotherType')
   let startTime = wx.getStorageSync('startTime');
   let shengrenTime = wx.getStorageSync('shengrenTime');
   let mentalTime = wx.getStorageSync('mentalTime');
   if(type==1){
    wx.setStorageSync('testType',1);
    wx.setStorageSync('paperId',anotherType);
   }else{
    wx.setStorageSync('testType',3);
    wx.setStorageSync('paperId',mentalId);
   }
   const qualifyDuration =wx.getStorageSync('qualifyDuration')||0
   this.setData({
    duration: qualifyDuration
   })
   let id = anotherType
   if(type!=1){
      id = mentalId
   }
   this.setSubTime(type,startTime,shengrenTime,mentalTime)
   this.getPaper(id,userInfo.idcard,userInfo.unitId,type)
   this.setData({
    type: type
   })

  },
  countdowm(duration){
    const subTime = this.data.subTime||0
    let t = duration * 60 * 1000 - subTime
    if(t<= 0){
      if(this.data.timer){
         clearInterval(this.data.timer)
      }
      this.submitAnswer()
      this.setData({
        timeRemain: '考试时间结束!'
      })
      return
    }
    const timer = setInterval(()=>{
      if (t > 0) {
        let hour = Math.floor((t / 3600000) % 24)
        let min = Math.floor((t / 60000) % 60)
        let sec = Math.floor((t / 1000) % 60)
        hour = hour < 10 ? '0' + hour : hour
        min = min < 10 ? '0' + min : min
        sec = sec < 10 ? '0' + sec : sec
        let format = ''
        if (hour > 0) {
          format = `${hour}:${min}:${sec}`
        }
        if (hour <= 0) {
          format = `00:${min}:${sec}`
        }
        this.setData({
          timeRemain: format
        })
        t = t - 1000
      } else {
        clearInterval(timer)
        this.submitAnswer()
        this.setData({
          timeRemain: '考试时间结束!'
        })
      }
    }, 1000)
    this.setData({
      timer
    })
  },
submitForm(){
  const {answerList,questionList} = this.data 
  if (answerList.length === questionList.length) {
    this.submitAnswer()
  }else{
    wx.showModal({
      title: '提示',  // 提示的标题
      content: '有试题未作答是否要提交考试！',  // 提示的内容
      confirmText: '确定', // 确认按钮的文字，默认：确定
      cancelText:'取消',   // 取消按钮的文字，默认：取消
      success:(res)=> {
      if (res.confirm) {
        this.submitAnswer()
      }
    }
   });
 }
},
submitAnswer(){
  let {answerList,questionList,type} = this.data 
  if(!questionList||questionList.length===0){
    return
  }
  if(!answerList||answerList.length===0){
    const result = {
      serialNumber: '-',
      score: 0,
    }
    this.radioChange('',result)
  }
  let userInfo = wx.getStorageSync("userInfo");

  const param = {
    qualifyAnswerList: this.data.answerList,
    testId: this.data.testId,
    idCard: userInfo.idcard,
    userName: userInfo.name,
    areaId: userInfo.areaId,
    answerWork: userInfo.unitId
  }
 ajax.postMethod('qualify/result/wx/batchAdd',param,'答案提交中...').then((res)=>{
  if (res.code === 200 || res.code === 230) {
      wx.showToast({
          title: '提交成功',
          icon:'none'
      })
      if(type==1){
        wx.reLaunch({
          url: '../topic-shengren-end/topic-shengren-end',
        })
      }else{
        wx.reLaunch({
          url: '../end/end',
        })
      }
   }else{
    wx.showToast({
      title: res.msg,
      icon:'none'
    })
   }
 })
},
setSubTime(type,startTime,shengrenTime,mentalTime){
  let time = 0; 
  let subTime =0
  const now = Date.now()
  const duration = this.duration
  if(startTime&&type==1){
   subTime = now-startTime - 40*60*1000
  }else{
    subTime = now-startTime - 40*60*1000-parseInt(duration)*60*100
  }
 if(type==1){
    if(!shengrenTime){
      shengrenTime = new Date().getTime();
      if(subTime>0){
        shengrenTime = shengrenTime - subTime
      }
      time = shengrenTime
      wx.setStorageSync('shengrenTime',shengrenTime);
    }else{
      time = shengrenTime
    }
  }else{
    if(!mentalTime){
      mentalTime = new Date().getTime();
      if(subTime>0){
        mentalTime = mentalTime - subTime
      }
      time = mentalTime
      wx.setStorageSync('mentalTime',mentalTime);
    }else{
      time = mentalTime
    }
  }
  this.setData({
     subTime,
     time
   })
  },
  getPaper(testId,idCard,answerWork,type){
    const fristTime = this.data.time
    let subTime = 0;
    if(fristTime>0){
       subTime = new Date().getTime() - fristTime
    }
    this.setData({
      subTime
     })
    ajax.getMethod('qualify/paper/getWxDetail/'+testId+'/'+idCard+'/'+answerWork,{},'试题加载中...').then(res=>{
      this.setData({
        paperDetail: res.data,
        questionList:  res.data.questionList,
        question: res.data.questionList[0],
        testId: testId,
        number:1,
        total: res.data.questionList.length,
        nextShow: res.data.questionList.length>1? true: false,
        percent: (1/res.data.questionList.length)*100
      })
      this.countdowm(res.data.duration)
      if(type==1){
        wx.setStorageSync('qualifyDuration',res?.data?.duration??0)
      }
    })
  },
  nextQuestion(){
     const {answerResult,question,answerList,questionList} = this.data
     if (answerResult.questionId != question.id) {
       wx.showToast({
          title: '当前题目未作答',
          icon:'none'
       })
       return
     }
     let number = this.data.number
     number++
     this.setData({
      number
     })
     this.setData({
      percent:((answerList.length+1)/ questionList.length)*100,
      question: questionList[number-1]
     })
     if(number >=questionList.length ){
       this.setData({
        nextShow: false
       })
     }else{
       this.setData({
        nextShow: true
       })
     }
  },
  // 单选
  radioChange(e,result) {
    let answerResult;
    const question = this.data.question
     if(result){
       answerResult = {
        questionId: question.id,
        answer: result.serialNumber,
        score: result.score,
        testId: this.data.testId
      }
     }else{
      const serialNumber = e.detail.value
      const optionList = [...question.optionList] 
      const result = optionList.find(item=>item.serialNumber===serialNumber)
      // 更新选项的checked状态
      optionList.forEach(item => {
        item.checked = item.serialNumber === serialNumber;
      });  
      answerResult = {
         questionId: question.id,
         answer: result.serialNumber,
         score: result.score,
         testId: this.data.testId
      }
      this.setData({
        'question.optionList': optionList
       })
     }
     this.setData({
      answerResult: answerResult
     })
     const answerList = this.data.answerList
    
     const info = answerList.find(item=>item.questionId == answerResult.questionId);
     let add = true
     if(info){
      info.answer = answerResult.answer
      info.score = answerResult.score
      add = false
     }
     if (add) {
       answerList.push(answerResult)
    }
    this.setData({
      answerList: answerList
    })
  },
  onUnload(){
    const timer = this.data.timer
    if(timer){
      clearInterval(timer)
      this.setData({
        timer: null
      })
    }
  }
});